package Persistence;

import java.sql.ResultSet;

/**
 * Mapper responsible for everything in relation to user accounts
 * 
 * @author kenneth
 */
public class UserMapper {
    
    private final DatabaseConnection databaseConnection;
    
    /**
     * Constructor
     *
     * @param databaseConnection The connection with the database
     */
    public UserMapper(DatabaseConnection databaseConnection) {
        this.databaseConnection = databaseConnection;
    }

    /**
     * Checks if the email & password are correct
     *
     * @param email The email address of the user
     * @param password The password of the user
     * @return True if correct
     */
    public boolean authenticateUser(String email, String password) {
        boolean userExists = false; 
        databaseConnection.openConnection();
        try {   
            ResultSet res = databaseConnection.executeQuery("SELECT email FROM users WHERE email = '" + email + "' AND paswoord = '" + password + "';");
            if(res.next())
                userExists = true;
        } catch (Exception e) {
            e.printStackTrace();
        }    
        databaseConnection.closeConnection();
        return userExists;
    }
    
    /**
     * Tries to register a user with the server
     * 
     * @param email The email address of the user
     * @param password The password of the user
     * @return True if the registration succeeded
     */
    public boolean registerUser(String email, String password) {
        boolean registerSuccess = false;
        databaseConnection.openConnection();
        try {
            ResultSet res = databaseConnection.executeQuery("SELECT email FROM users WHERE email = '" + email + "'");
            if(!res.next()) {
                databaseConnection.executeUpdate("INSERT INTO users (email, paswoord) VALUES ('" + email + "','" + password + "')");
                registerSuccess = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        databaseConnection.closeConnection();
        return registerSuccess;
    }
    
    /**
     * Resets the password from a user
     * 
     * @param email The email address of the user
     * @return True if the password reset succeeded
     */
    public boolean resetPasswordFromUser(String email) {
        return false;
    }
    
}
